package kcms.user.dao.impl;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import kcms.db.User;
import kcms.user.dao.UserDAO;

@Repository
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO{
	@Resource
	private SessionFactory sessionFactory;

    /*public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }*/
	@Resource
	public void setMySessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

    public boolean addUser(User user) {
    	try{
    	this.getHibernateTemplate().save(user);
    	return true;
    	}
    	catch(Exception ex){
    		ex.printStackTrace();
    		return false;
    	}
    	//sessionFactory.openSession().save(user);
	} 
    public boolean updateUser(User user){
    	try{
    	this.getHibernateTemplate().update(user);
    	return true;
    	}catch(Exception ex){
    		ex.printStackTrace();
    		return false;
    	}
    }
    @SuppressWarnings("unchecked")
	public List<User> getAllUser(){
        String hql="from User";
        return (List<User>) this.getHibernateTemplate().find(hql);
    }
    
    @SuppressWarnings("unchecked")
	public List<User> getUser(String id){
    	//Object values[]={id,password};
    	String queryString="from User u where u.id=?";
    	return (List<User>) this.getHibernateTemplate().find(queryString,id);
    }
    public void setValid(String uid){
    	User tempusr;
    	if((!(this.getHibernateTemplate().find("from User u where u.id=?", uid)).isEmpty())){
    		tempusr=(User) this.getHibernateTemplate().find("from User u where u.id=?", uid).get(0);
    		tempusr.setIsvalid(true);
    		this.getHibernateTemplate().saveOrUpdate(tempusr);
    	}
    	
    }

}
